const template = require("art-template")
const fs = require("fs")
const path = require("path")
const http = require("http")
const url = require("url")
// // 基于模板名渲染模板
// template(filename, data);
//
// // 将模板源代码编译成函数
// template.compile(source, options);
//
// // 将模板源代码编译成函数并立刻执行
// template.render(source, data, options);
function testTemplate() {
    let result = template.render("hello,{{name}}", {
        name: "黄鑫"
    })
    console.log(result);
}

function testTemplate2() {
    fs.readFile(path.join("page/index.html"), function (error, data) {
        if (error) {
            return console.log("读取错误")
        }
        let result = template.render(data.toString(), {name: "黄鑫"})
        console.log(result);
    })
}

/**
 * 读取文件并渲染返回
 */
function testTemplate3() {
    http.createServer(function (request, respone) {
        if (request.url === '/') {

            fs.readdir(path.join("page/"), function (error, files) {
                if (error) {
                    return console.log("读取错误")
                }
                //读取文件
                fs.readFile(path.join("page/index.html"), function (error, data) {
                    //模板渲染返回
                    let page = template.render(data.toString(), {name: files})
                    respone.end(page)
                })
            })
        } else {
            respone.end("404")
        }
    }).listen(10000)
}


const querystring = require("querystring");
const util = require("util");
function testPost() {
    http.createServer(function (request,respone) {

        let postData ='';
        request.on("data", function (postDataChunk) {
            //拼接post传过来的参数
            postData += postDataChunk;
        });

        request.on("end", function () {
            console.log('数据接收完毕');
            //转成对象
            let params = querystring.parse(postData.toString());//GET & POST  ////解释表单数据部分{name="zzl",email="zzl@sina.com"}
            //获取参数
            console.log("msg:",params["msg"]);
            respone.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//设置response编码为utf-8
            respone.write(util.inspect(params));
            respone.end("数据提交完毕");
        });
    }).listen(1000)
}











